package org.smart4j.framework.common.helper;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.smart4j.framework.common.bean.FormParam;
import org.smart4j.framework.common.bean.Param;
import org.smart4j.framework.common.constant.ConfigConstant;
import org.smart4j.framework.common.util.CodecUtil;
import org.smart4j.framework.common.util.StreamUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @author YooLin1c
 * @version 1.0.0
 * @since 2018-02-07 21:02
 */
public class RequestHelper {

    public static Param getParam(HttpServletRequest request) throws IOException {
        List<FormParam> formParamList = new ArrayList<>();
        formParamList.addAll(parseParameterNames(request));
        formParamList.addAll(parseInputStream(request));
        return new Param(formParamList);
    }

    private static List<FormParam> parseInputStream(HttpServletRequest request) {
        List<FormParam> formParams = new ArrayList<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            String[] parameterValues = request.getParameterValues(parameterName);
            String parameterValue = null;
            if (ArrayUtils.isNotEmpty(parameterValues)) {
                if (parameterValues.length > 1) {
                    StringBuilder sb = new StringBuilder();
                    for (String value : parameterValues) {
                        sb.append(value).append(ConfigConstant.SEPARATOR);
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    parameterValue = sb.toString();
                } else {
                    parameterValue = parameterValues[0];
                }
            }
            formParams.add(new FormParam(parameterName, parameterValue));
        }
        return formParams;
    }

    private static List<FormParam> parseParameterNames(HttpServletRequest request) throws IOException {
        List<FormParam> formParams = new ArrayList<>();
        //获取请求路径的请求参数
        String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
        if (StringUtils.isNotBlank(body)) {
            String[] params = body.split("&");
            if (ArrayUtils.isNotEmpty(params)) {
                for (String param : params) {
                    String key = param.substring(0, param.indexOf("="));
                    if (StringUtils.isNotBlank(key)) {
                        String value = param.substring(param.indexOf("=") + 1, param.length());
                        formParams.add(new FormParam(key, value));
                    }
                }
            }
        }
        return formParams;
    }
}
